package com.aquarium.ui;

import java.util.Observable;
import java.util.Observer;

import com.aquarium.R;
import com.aquarium.bt.BTManager;
import com.aquarium.bt.DataInterpreter;
import com.aquarium.bt.DataStruct;
import com.aquarium.config.BTCommand;
import com.aquarium.security.SecurityManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioButton;

public class ModelSwitchActivity extends Activity implements Observer {
	private static final String TAG = "ModelSwitchActivity";

	private static final int TIMEOUT_VALUE = 5000;

	private static final int MESSAGE_REQUEST_COMMUNICATE = 0x12;
	private static final int MESSAGE_RECEIVE_DATA_TIMEOUT = 0x15;
	private static final int MESSAGE_COMMUNICATE_SUCCESS = 0x16;
	private static final int MESSAGE_COMMUNICATE_FAIL = 0x17;
	private static final int MESSAGE_COMMUNICATE_IN_PROGRESS = 0x19;

	private Context mContext;

	private BTManager mBtManager;

	private ImageView mBackButton;

	private Button mFeedingModeButton;
	private Button mMaintenanceModeButton;

	private RadioButton mFeedingModeCloseButton;
	private RadioButton mMaintenanceModeCloseButton;

	private boolean bFeedingModeOpen = false;
	private boolean bMaintenanceModeOpen = false;

	private ProgressDialog mProgressDialog;

	private byte[] mSetFeedingModeCommand;
	private byte[] mSetMaintenanceModeCommand;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.mode_setting);
		mContext = ModelSwitchActivity.this;

		mBtManager = BTManager.getInstance();
		mBtManager.addObserver(this);

		mBackButton = (ImageView) findViewById(R.id.back);
		mFeedingModeButton = (Button) findViewById(R.id.feeding_do_now_btn);
		mMaintenanceModeButton = (Button) findViewById(R.id.maintenance_do_now_btn);

		mFeedingModeCloseButton = (RadioButton) findViewById(R.id.feeding_close_radio_btn);
		mMaintenanceModeCloseButton = (RadioButton) findViewById(R.id.maintenance_close_radio_btn);

		mFeedingModeCloseButton.setChecked(true);
		mMaintenanceModeCloseButton.setChecked(true);

		setListener();

	}

	private void setListener() {
		mBackButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
			}
		});

		mFeedingModeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSetFeedingModeCommand = BTCommand
						.getSetFeedingModeCommand(bFeedingModeOpen);

				mBtManager.sendData(DataInterpreter
						.unpack(mSetFeedingModeCommand));
				mHandler.sendEmptyMessageDelayed(MESSAGE_RECEIVE_DATA_TIMEOUT,
						TIMEOUT_VALUE);
				mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_IN_PROGRESS);

				// test code TODO
//				SystemClock.sleep(1000);
//				mBtManager.receivePseudoData(mSetFeedingModeCommand);

			}
		});

		mMaintenanceModeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSetMaintenanceModeCommand = BTCommand
						.getSetMaintenanceModeCommand(bMaintenanceModeOpen);

				mBtManager.sendData(DataInterpreter
						.unpack(mSetMaintenanceModeCommand));
				mHandler.sendEmptyMessageDelayed(MESSAGE_RECEIVE_DATA_TIMEOUT,
						TIMEOUT_VALUE);
				mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_IN_PROGRESS);

				// test code TODO
//				SystemClock.sleep(1000);
//				mBtManager.receivePseudoData(mSetMaintenanceModeCommand);

			}
		});
	}

	public void onRadioButtonClicked(View view) {
		boolean checked = ((RadioButton) view).isChecked();

		switch (view.getId()) {
		case R.id.feeding_open_radio_btn:
			if (checked)
				bFeedingModeOpen = true;
			break;
		case R.id.feeding_close_radio_btn:
			if (checked)
				bFeedingModeOpen = false;
			break;
		case R.id.maintenance_open_radio_btn:
			if (checked)
				bMaintenanceModeOpen = true;
			break;
		case R.id.maintenance_close_radio_btn:
			if (checked)
				bMaintenanceModeOpen = false;
			break;
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MESSAGE_REQUEST_COMMUNICATE:

				break;
			case MESSAGE_COMMUNICATE_IN_PROGRESS:
				showProgressDialog();
				break;

			case MESSAGE_COMMUNICATE_SUCCESS:
				mProgressDialog.dismiss();
				showToast(getString(R.string.set_success));
				break;
			case MESSAGE_COMMUNICATE_FAIL:
				mProgressDialog.dismiss();
				showFailDialog(getString(R.string.set_fail));
				break;
			case MESSAGE_RECEIVE_DATA_TIMEOUT:
				mProgressDialog.dismiss();
				showFailDialog(getString(R.string.set_timeout));
				break;
			default:
				break;
			}

		};
	};

	@Override
	protected void onDestroy() {
		mBtManager.deleteObserver(this);
		super.onDestroy();
	}

	private void showFailDialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = this.getLayoutInflater();
		final View authFailView = inflater.inflate(
				R.layout.dialog_authentication_fail, null);
		((TextView) authFailView.findViewById(R.id.auth_fail_message))
				.setText(message);

		builder.setView(authFailView)
				.setTitle(getText(R.string.error))
				.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
							}
						}).create().show();
	}

	private void showProgressDialog() {
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(getText(R.string.please_wait));
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}

	private void showToast(String content) {
		Toast.makeText(mContext, content, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void update(Observable observable, Object data) {
		if (observable instanceof BTManager) {
			// timeout already.
			if (!mHandler.hasMessages(MESSAGE_RECEIVE_DATA_TIMEOUT)) {
				return;
			}
			final DataStruct receivedData = (DataStruct) data;
			byte[] responseData = DataInterpreter.pack(receivedData);

			if (receivedData.prefix == 0x5a && receivedData.id == 0x01
					&& receivedData.code == 0x6d && receivedData.length == 0x01
					&& receivedData.data.length == 1) {
				Log.d(TAG, "get responce data of set alias");

				mHandler.removeMessages(MESSAGE_RECEIVE_DATA_TIMEOUT);

//				if (responseData[4] == 0x01) {
					if (receivedData.data[0] == 0x00) {
						mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_SUCCESS);
					} else {
						mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_FAIL);
					}
//				} else if (responseData[4] == 0x02) {
//					if (responseData[5] == mSetMaintenanceModeCommand[5]) {
//						mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_SUCCESS);
//					} else {
//						mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_FAIL);
//					}
//				} else {
//					mHandler.sendEmptyMessage(MESSAGE_COMMUNICATE_FAIL);
//				}

			}
		}
	}
}
